package org.roger.scorer;

import java.io.IOException;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.Scorer;
import org.roger.util.DistanceUtil;

/**
 * 自定义分数（距离定义成分数）
 * @author luoweiyi
 */
public class DistanceScorer extends Scorer {

	protected final IndexReader reader;
	private int doc = -1;
	protected final int maxDoc;
	protected boolean checkDeletes;
	private DocIdSetIterator disi;

	public DistanceScorer(IndexReader reader) {
		super(null);
		this.reader = reader;
		this.maxDoc = reader.maxDoc();
		setCheckDeletes(true);
		disi = DocIdSetIterator.all(maxDoc);
	}

	@Override
	public float score() throws IOException {
		String location = reader.document(doc).get("location");
		if (location != null) {
			int x = Integer.parseInt(location.split(",")[0]);
			int y = Integer.parseInt(location.split(",")[1]);
			return (float) DistanceUtil.getDistance(x, y);
		}
		return 0;
	}

	@Override
	public int freq() throws IOException {
		return 1;
	}

	public void setCheckDeletes(boolean checkDeletes) {
		this.checkDeletes = checkDeletes && reader.hasDeletions();
	}

	@Override
	public int docID() {
		return doc;
	}

	@Override
	public DocIdSetIterator iterator() {
		return disi;
	}
}
